package com.example.sharesinfo;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.example.sharesinfo.base.BaseApp;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.TokenBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.fragment.CommunityFragment;
import com.example.sharesinfo.fragment.IndexFragment;
import com.example.sharesinfo.fragment.InformationFragment;
import com.example.sharesinfo.fragment.OptionalFragment;
import com.example.sharesinfo.fragment.StockFragment;
import com.example.sharesinfo.helper.ActivityHelper;
import com.example.sharesinfo.manager.CloudManager;
import com.example.sharesinfo.service.CloudService;
import com.example.sharesinfo.ui.ChatRecordActivity;
import com.example.sharesinfo.utils.CleanMessageUtil;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;
import com.squareup.leakcanary.RefWatcher;

import java.util.HashMap;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;


public class MainActivity extends BaseUIActivity {
    //定义控件
    private RadioButton main_home;
    private RadioButton main_market;
    private RadioButton main_optional;
    private RadioButton main_community;
    private RadioButton main_information;
    private RadioGroup mainRadioGroup;
    public int wdMessage = 0;
    //定义Fragment
    private CommunityFragment mCommunityFragment = null;     //社区

    private IndexFragment mIndexFragment = null;             //首页

    private InformationFragment mInformationFragment = null; //资讯

    private OptionalFragment mOptionalFragment = null;       //自选

    private StockFragment mStockFragment = null;     //行情

    private boolean temp = true;
    private int index;
    private int currentTabIndex;
    private Disposable disposable;
    private Fragment[] fragments = {new IndexFragment().getFragment(),
            new StockFragment().getFragment(),
            new OptionalFragment().getFragment(),
            new CommunityFragment().getFragment(),
            new InformationFragment().getFragment()};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityHelper.getInstance().addActivity(MainActivity.this);
        initView();

    }

    private void initView() {
        main_home = findViewById(R.id.radio_button_home);
        main_market = findViewById(R.id.radio_button_market);
        main_optional = findViewById(R.id.radio_button_optional);
        main_community = findViewById(R.id.radio_button_community);
        main_information = findViewById(R.id.radio_button_information);
        RadioButton[] rbs = {main_home, main_market, main_optional, main_community, main_information};
        for (RadioButton rb : rbs) {
            //挨着给每个RadioButton加入drawable限制边距以控制显示大小
            Drawable[] drs = rb.getCompoundDrawables();
            //获取drawables
            Rect r = new Rect(0, 0, drs[1].getMinimumWidth() / 3, drs[1].getMinimumHeight() / 3);
            //定义一个Rect边界
            drs[1].setBounds(r);
            rb.setCompoundDrawables(null, drs[1], null, null);
        }
        initFragment();
        changeMainFragment(0);
        checkToken();
        //获取Token 需要三个参数 1.用户id 2.头像地址 3.昵称


    }

    private void checkToken() {
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN, "");
        LogUtils.i("CloudManager" + "token()" + token);
        if (!TextUtils.isEmpty(token)) {
            //启动云服务器去链接融云服务
            startCloudService();
        } else {
            createToken();
        }
    }

    private void createToken() {
        /**
         * 1.后台获取融云Token
         * 2.链接融云
         * */
        LogUtils.i("CloudManager" + "createToken");
        final HashMap<String, String> map = new HashMap<>();
        map.put("userId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        map.put("name", SpUtils.getInstance().getString(Constants.SP_USER_NAME, ""));
        map.put("portraitUri", SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, ""));
        //通过OkHttp请求Token,异步Rxjava
        disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                //执行请求过程
                String json = OkHttpUtils.getInstance().postCloudToken(map);
                emitter.onNext(json);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.newThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        LogUtils.i("CloudToken" + s);
                        parsingCloudToken(s);

                    }
                });
    }

    private void parsingCloudToken(String s) {
        LogUtils.i("CloudManager" + "parsingCloudToken");
        TokenBean bean = new Gson().fromJson(s, TokenBean.class);
        if (bean.getCode() == 200) {
            if (!TextUtils.isEmpty(bean.getToken())) {
                //保存token
                SpUtils.getInstance().putString(Constants.SP_TOKEN, bean.getToken());
                startCloudService();
            }
        }
    }

    private void startCloudService() {
        LogUtils.i("CloudManager" + "startCloudService");
        startService(new Intent(this, CloudService.class));
    }

    private void initFragment() {
        mainRadioGroup = findViewById(R.id.main_home_bottom_bar);
        mainRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int arg1) {
                //遍历RadioGroup 里面所有的子控件。
                for (int i = 0; i < group.getChildCount(); i++) {
                    //获取到指定位置的RadioButton
                    RadioButton rb = (RadioButton) group.getChildAt(i);
                    //如果被选中
                    if (rb.isChecked()) {
                        index = i;
                        break;
                    }
                }
                if (currentTabIndex != index) changeMainFragment(index);
                currentTabIndex = index;
            }
        });

    }


    private void changeMainFragment(int index) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = supportFragmentManager.beginTransaction();
        transaction.hide(fragments[currentTabIndex]);
        if (!fragments[index].isAdded()) {
            transaction.add(R.id.main_container, fragments[index]);
        }
        transaction.show(fragments[index]).commit();

    }

    /**
     * 防止重叠
     * 当应用的内存紧张的时候，系统会回收掉Fragment对象
     * 再一次进入的时候会重新创建Fragment
     * 非原来对象，我们无法控制，导致重叠
     */
    @Override
    public void onAttachFragment(Fragment fragment) {
        if (mCommunityFragment != null && fragment instanceof CommunityFragment) {
            mCommunityFragment = (CommunityFragment) fragment;
        }
        if (mStockFragment != null && fragment instanceof StockFragment) {
            mStockFragment = (StockFragment) fragment;
        }
        if (mIndexFragment != null && fragment instanceof IndexFragment) {
            mIndexFragment = (IndexFragment) fragment;
        }
        if (mInformationFragment != null && fragment instanceof InformationFragment) {
            mInformationFragment = (InformationFragment) fragment;
        }
        if (mOptionalFragment != null && fragment instanceof OptionalFragment) {
            mOptionalFragment = (OptionalFragment) fragment;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = BaseApp.getRefWatcher(this);//1
//        refWatcher.watch(this);
    }
}
